package net.obxlabs.tweetpad.behaviour;

import net.nexttext.*;
import net.nexttext.behaviour.*;
import net.nexttext.property.*;
import net.obxlabs.tweetpad.*;

/**
 * Swaps a TextObjectGroup with a new one which is its synonym. This works using
 * the dictionary/Thesaurus library. It only work on groups built with the 
 * Linguist TextObjectBuilder. The way to use it is to apply the behaviour to
 * the glyphs.
 * 
 * $Id:AbstractSwap.java 16 2007-11-27 10:50:46Z prisonerjohn $
 */
public abstract class AbstractSwap extends AbstractAction {
	public static final int OFFSET_X = 0;  // TODO consolidate this with Maker+Shuffle+ReorderSiblings
	
	protected Book book;
	protected Maker builder;
	
	public AbstractSwap(Book book, Maker builder) {
		this.book = book;
		this.builder = builder;
	}
	
	public abstract ActionResult behave(TextObject to);
	
	public void repositionChildren(TextObjectGroup tog, TextObject oldTo, TextObject newTo) {
		// XXX I don't know why I need a -1 here... Maybe the book.removeObject() hasn't occured yet?
    	TextObject[] orderedChildren = new TextObject[tog.getNumChildren()-1];
    	
    	// create an ordered list of the children
    	for (TextObject child = tog.getLeftMostChild(); child != null; child = child.getRightSibling()) {
    		int loc = (int)((NumberProperty)child.getProperty("ShuffleLocation")).get();
    		orderedChildren[loc-1] = child;
    	}
    	
    	// move every child where it belongs on the line
    	double currX = 0;
    	double y = orderedChildren[0].getPosition().get().y;
    	for (int i=0; i < orderedChildren.length; i++) {
    		try {
    			orderedChildren[i].getPosition().set(new Vector3(currX, y));
    			// XXX for some reason, the old TO stays in the hierarchy, quick hack until I figure out why
    			if (orderedChildren[i] == oldTo) {
    				currX += newTo.getBounds().width+OFFSET_X;
    			} else {
    				currX += orderedChildren[i].getBounds().width+OFFSET_X;
    			}
    		} catch (NullPointerException e) {
    			// XXX some null shit at the end of the tree, don't ask me why
    			System.out.println("AbstractSwap: orderedChildren["+i+"] is null...");
    			continue;
    		}
    	}
    }
}
